import os
# import time
# import numpy as np
import pandas as pd
import yagmail
import configparser
import tkinter as tk
from tkinter import filedialog
import re
import traceback



# county_list = [9657, 9658, 9659, 9660, 9661, 9662, 9663, 9664, 9665, 9666, 9667, 9668]
# county_list = ['9657', '9658', '9659', '9660', '9661', '9662', '9663', '9664', '9665', '9666', '9667', '9668']


def remove_bom(content):
    # 移除UTF-8 BOM（EF BB BF）
    content = re.sub(r'^\xef\xbb\xbf', '', content, 1)
    # 移除UTF-16 BOM（FF FE 或 FE FF）
    content = re.sub(r'^\xfe\\xff|\xfffe', '', content, 1)
    return content


def create_send_dir(source_path):
    # curr_dir = os.getcwd()
    new_path = 'send_dir'
    new_path = os.path.join(source_path, new_path)
    try:
        if not os.path.exists(new_path):
            os.makedirs(new_path)
    except OSError as e:
        print('====创建失败====', e)


def email_list(data, county_code):
    # inplace=False, 删除后返回一个副本，True为在原数据上删除
    to_cate_list = data.drop_duplicates(subset=['CATEGORY'], inplace=False)['CATEGORY'].tolist()
    # print(to_cate_list)
    # print('---email_list: ', data)
    # 定义空字典
    to_dic = {}
    # print('COUNTY_CODE: ', county_code, type(county_code))
    for item in to_cate_list:
        tmp = data[data['CATEGORY']==item]
        # print('--len tmp: ', len(tmp), tmp)
        tmpp = tmp[tmp['CATE']==county_code]
        # print('--tmp: ', tmp)
        
        # 获取对应emial地址和姓名
        # print('--len tmpp: ', len(tmpp), type(tmpp), tmpp)
        for index, row in tmpp.iterrows():
            # print('======row----: ', row)
            # print('--', row['EMAIL_ADDR'])
            # print('--', row['EMAIL_NAME'])
            tmp_addr = row['EMAIL_ADDR']
            tmp_name = row['EMAIL_NAME']
            # # tmp_dic = {tmpp['EMAIL_ADD'], tmpp['EMAIL_NAME']}
            to_dic.setdefault(tmp_addr, tmp_name)
    # print('--to_dic: ', to_dic)    
    return to_dic


def email_common(common_file):
    # res = pd.read_excel(common_file)
    # print('----cc', common_file)
    cc_dic = {}
    for i in range(len(common_file)):
        cc_dic.setdefault(common_file.iloc[i]['EMAIL_ADDR'], common_file.iloc[i]['EMAIL_NAME'])
    return cc_dic


def choose_file():
    # # 使用askopenfilename()函数弹出文件选择对话框
    file_path = filedialog.askopenfilename()
    if file_path:
        print('您选择的文件是：', file_path)
        return file_path
    else:
        print('您未选择文件')
        return ''


def choose_folder():
    # askdirectory()函数弹出文件夹选择对话框
    folder_path = filedialog.askdirectory()
    if folder_path:
        print('您选择的文件夹是：', folder_path)
        return folder_path
    else:
        print('您未选择文件夹')
        return ''


def yagmail_send(mail_addr, mail_pwd, mail_host, to_list, cc_list, title, contents, attachments):
    print('----邮件发送内容-收件人: ', to_list)
    print('----邮件发送内容-抄送人: ', cc_list)
    print('----邮件发送内容-附件: ', attachments)
    
    yag_server = yagmail.SMTP(user=mail_addr, password=mail_pwd, host=mail_host)
    yag_server.send(to=to_list, cc=cc_list, subject=title, contents=contents, attachments=attachments)
    print('-----------------邮件发送成功！')


def source_split_mail(mail_addr, mail_pwd, mail_host, source_path, source_file, title, content, category, cate_list, to_data, cc_data, cc_common_list,  attach_list):
    try:
        source_data = pd.read_excel(source_file)
    except Exception as e:
        print('错误e：', e)
        try:
            source_data = pd.read_csv(source_file, encoding='gbk')
        except Exception as e1:
            print('gbk csv 错误e1：', e1)
            try:
                source_data = pd.read_csv(source_file, encoding='utf-8')
            except Exception as e2:
                print('utf8 csv 错误e2：', e2)
                try:
                    source_data = pd.read_csv(source_file, encoding='mbcs')
                except Exception as e3:
                    print('mbcs 错误：', e3) 
    # print(source_data)

    # print('---attach_list', type(attach_list), attach_list)


    # print('---cc_common_list: ', cc_common_list)
    for item in cate_list:
        file_list = []
        # print('--attach_list', attach_list)
        # file_list = attach_list
        item_tmp = int(item.strip())
        to_list = email_list(to_data, item_tmp)
        try:
            cc_list = email_list(cc_data, item_tmp)
        except Exception as e:
            cc_list = {}
        try:
            cc_list.update(email_common(cc_common_list))
        except Exception as e:
            cc_list = email_common(cc_common_list)
        # print('---to_list: ', item, to_list)
        # print('---cc_list: ', item, cc_list)
        print('\n\n----------开始源数据拆分处理----------  ', item)
        res = source_data[source_data[category]==int(item.strip())]
        temp_path = source_path + '/send_dir/' + str(item) + '-' + '数据文件' + '-' + str(len(res)) + '.csv.gz'
        print('--数据拆分保存路径: ', temp_path)
        res.to_csv(temp_path, index=False, compression='gzip')
        # print(res)
        file_list.append(temp_path)
        # print('--attach_list: ', attach_list)
        file_list = file_list + attach_list
        # print('--file_list: ', file_list)

        try:
            print('------开始发送邮件-------')
            yagmail_send(mail_addr=mail_addr, mail_pwd=mail_pwd, mail_host=mail_host, to_list=to_list, cc_list=cc_list, title=title, contents=content, attachments=file_list)
        except Exception as e:
            print('------YAGMAIL SENT ERROR--------   : ', e)
            traceback.print_exc()

    print('------任务完成-------')
        

def source_split(source_path, source_file, category, cate_list):
    try:
        source_data = pd.read_excel(source_file)
    except Exception as e:
        print('错误e：', e)
        try:
            source_data = pd.read_csv(source_file, encoding='gbk')
        except Exception as e1:
            print('gbk csv 错误e1：', e1)
            try:
                source_data = pd.read_csv(source_file, encoding='utf-8')
            except Exception as e2:
                print('utf8 csv 错误e2：', e2)
                try:
                    source_data = pd.read_csv(source_file, encoding='mbcs')
                except Exception as e3:
                    print('mbcs 错误：', e3) 
    print(source_data)

    for item in cate_list:
        print('--------------------', item)
        res = source_data[source_data[category]==int(item.strip())]
        temp_path = source_path + '/send_dir/' + str(item) + '-' + '数据文件' + '-' + str(len(res)) + '.csv.gz'
        # print('--temp_path: ', temp_path)
        res.to_csv(temp_path, index=False, compression='zip')

    print('------COMPLET-------')


def start():
    # 邮箱相关配置
    # config = email_config()
    with open('./config.ini', 'r', encoding='utf-8-sig') as f:
        config_content = f.read()
    config_content = remove_bom(config_content)
    config = configparser.ConfigParser()
    config.read_string(config_content)
    print('提示：如需从其他地方复制粘贴过来，请正常在其他地方复制，然后到本终端窗口右键一次即可粘贴成功！')
    print('******下一步******')


    # 创建一个Tkinter窗口对象，但不会显示
    root = tk.Tk()
    root.withdraw()
    print('请选择源数据文件目录：')
    print('******下一步******')
    source_path = ''
    while source_path == '':
        source_path = choose_folder()
    print('请选择源数据文件：')
    print('******下一步******')
    source_file= ''
    while source_file == '':
        source_file = choose_file()
    category = ''
    while category == '':
        category = input('请输入源数据文件需拆分的字段（英文需区别大小写）：')
    print('******下一步******')
    county_list = config.get('file_config', 'list').split(',')  # 收件人分类
    
    ## step2: 创建分类数据存储文件夹
    create_send_dir(source_path=source_path)

    if_mail = input('是否需要发送邮件Y/N：')
    if if_mail == 'Y' or if_mail == 'y':
        mail_addr = config.get('mail_content', 'user_mail')
        mail_pwd = config.get('mail_content', 'user_pwd')
        mail_host = config.get('mail_content', 'host')

        title = config.get('mail_content', 'title')
        content = config.get('mail_content', 'content')
        sign = config.get('mail_content', 'sign')
        tag = '<br><br>&copy; 2024. Powered By Zhyoung.'

        print('请选择收件人表格文件：')
        print('******下一步******')
        to_file = ''
        while to_file == '':
            to_file = choose_file()
        to_file_res = '' if to_file =='' else pd.read_excel(to_file)
        # print('--to_file_res: ', to_file_res)
        print('请选择抄送人表格文件：')
        print('******下一步******')
        cc_file = choose_file()
        cc_file_res = '' if cc_file =='' else pd.read_excel(cc_file)
        # print('--cc_file_res: ', cc_file_res)
        print('请选择共同抄送人表格：')
        print('******下一步******')
        cc_common_file = choose_file()
        cc_common_list = '' if cc_common_file =='' else pd.read_excel(cc_common_file)
        # print('--cc_common_list: ', cc_common_list)
        print('请选择需发送的附件，若无则在弹框中选择取消：')
        print('******下一步******')
        attach_list_res = []
        while True:
            print('请选择邮件附件：')
            temp = choose_file() 
            if temp != '':
                attach_list_res.append(temp)
            else:
                break
        
        source_split_mail(mail_addr=mail_addr, mail_pwd=mail_pwd, mail_host=mail_host, source_path=source_path, 
                          source_file=source_file, title=title, content=content+sign+tag, category=category, cate_list=county_list, 
                          to_data=to_file_res, cc_data=cc_file_res, cc_common_list=cc_common_list, attach_list=attach_list_res)
    else:
        source_split(source_path=source_path, source_file=source_file, category=category, cate_list=county_list)


    input('按任意键结束')


if __name__ == '__main__':
    # yag_server = yagmail.SMTP(user='zhouyang1@jx.chinamobile.com', password='6837E0A2968EA5C87E00', host='smtp.jx.chinamobile.com')
    # yag_server.send(to='zhouyang1@jx.chinamobile.com', subject='ceshi')
    start()



